//
//  XJShopDetailViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/5/4.
//  Copyright © 2018年 Tzyang. All rights reserved.
//
#define kMargin10 10
#define kMargin5 5

#import "XJShopDetailViewController.h"
#import "XJShopDetailModel.h"
#import "RBTitleButton.h"
#import "XJAllCategoryViewController.h"

// Views


@interface XJShopDetailViewController ()<UIScrollViewDelegate>
// 店铺详情头部视图
@property(nonatomic, strong) UIImageView *headBgView;
@property(nonatomic, strong) UIImageView *shopIconIV; // 店铺iconIV
@property(nonatomic, strong) UILabel *shopTitleLB; // 店铺标题LB
@property(nonatomic, strong) UILabel *contentLB; // 经营内容Lb
@property(nonatomic, strong) UILabel *phoneAddressLB;// 手机号+地址LB
@property(nonatomic, strong) UIButton *dismissBtn; // 消失btn

/** 5-7 分类滚动view*/
@property(nonatomic, strong) UIScrollView *titleScrollView;
/**用于标记当前选中的btn*/
@property(nonatomic, strong) RBTitleButton *selectedBtn;
/**btn下面的指示器线条*/
@property(nonatomic, strong) UIView *indicateLine;

// model
@property(nonatomic, strong) XJShopDetailModel *shopModel;
/**店铺分类数据源*/
@property(nonatomic, strong) NSMutableArray<XJShopCategoryModel *> *shopCategoryArr;
// 大scrollView
@property (nonatomic, strong) UIScrollView *scrollView;

/**用来装RBTitleButton 取titleScrollView这玩意的指示图有 bug.明明只有四个偏偏变成6个。前两个还是UIImageView
 一定要记得懒加载。 对象不纯在。导致一堆bug
 */
@property(nonatomic, strong) NSMutableArray *btnArray;

@end

@implementation XJShopDetailViewController

#pragma mark - 一 lazy
- (NSMutableArray<XJShopCategoryModel *> *)shopCategoryArr {
    if (!_shopCategoryArr) {
        _shopCategoryArr = [NSMutableArray array];
    }
    return _shopCategoryArr;
}
- (NSMutableArray *)btnArray {
    if (!_btnArray) {
        _btnArray = [NSMutableArray array];
    }
    return _btnArray;
}

#pragma mark - 二 视图生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navTitle = @"店铺详情";
    
//    [self rb_addChildVCs];
    
//    [self createShopHeadView];
    
//    NSArray *titleArr = @[@"全部分类",@"分类一",@"水果",@"生活用品",@"分类三"];
//    [self createCategoryViewTitleArr:titleArr];
//
//    [self rb_setupScrollView];
//
//    [self rb_addChildViews];
//
    [self requestDianPuDetailData];
//
//    [self requestAllCategoryData];
}

#pragma mark - 三 加载子视图控制器 & 布局UI

//添加子视图控制器 根据服务器返回的数据动态创建子控制器
- (void)rb_addChildVCs:(NSArray *)shopCtyArr {
    
    if (shopCtyArr.count == 0) {
        return;
    }

    for (int i =0; i<shopCtyArr.count; i++) {
        XJShopCategoryModel *shopctyModel = shopCtyArr[i];
        
        XJAllCategoryViewController *allctyVC = [[XJAllCategoryViewController alloc] init];
        allctyVC.shopCategoryId = shopctyModel.shopCategoryId;
        
        [self addChildViewController:allctyVC];
    }
}

// 添加子视图控制器的views
- (void)rb_addChildViews {
    
    NSInteger index = self.scrollView.contentOffset.x / self.scrollView.rb_width;
    
    // 防崩溃处理:如果服务器没有返回数据。你还去取肯定炸
    if (self.childViewControllers.count == 0) {
        return;
    }
    
    XJAllCategoryViewController *childVC = self.childViewControllers[index];
    if ([childVC isViewLoaded]) {return;}
    
    childVC.view.frame = self.scrollView.bounds;
    [self.scrollView addSubview:childVC.view];
}


// 店铺详情headerView
- (void)createShopHeadView {
//    适配iPhoneX
    self.headBgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,KWidth , ADAPTHeight(150))];
    self.headBgView.userInteractionEnabled = YES;
    [self.view addSubview:self.headBgView];
    
    self.shopIconIV = [[UIImageView alloc] initWithFrame:CGRectMake(20, 50, ADAPTWidth(80), ADAPTHeight(80))];
    self.shopIconIV.layer.cornerRadius = 4.0;
    self.shopIconIV.layer.masksToBounds = YES;
    [self.headBgView addSubview:self.shopIconIV];
    
    CGFloat maxX =  CGRectGetMaxX(self.shopIconIV.frame);
    CGFloat minY =  CGRectGetMinY(self.shopIconIV.frame);
    // 用Masonry布局
    self.shopTitleLB = [[UILabel alloc] initWithFrame:CGRectMake(maxX + kMargin10, minY+kMargin5, ADAPTWidth(150), ADAPTHeight(20))];
//    self.shopTitleLB.text = @"幸福小铺";
    self.shopTitleLB.textColor = [UIColor whiteColor];
    self.shopTitleLB.font = [UIFont boldSystemFontOfSize:17.0];
    [self.headBgView addSubview:self.shopTitleLB];
    
    self.contentLB = [[UILabel alloc] initWithFrame:CGRectMake(maxX+kMargin10, CGRectGetMaxY(self.shopTitleLB.frame)+kMargin5, ADAPTWidth(200), ADAPTHeight(20))];
    self.contentLB.font = [UIFont systemFontOfSize:13.0];
    self.contentLB.textColor = [UIColor whiteColor];
//    self.contentLB.text = @"经营内容:女装 女鞋 服饰";
    [self.headBgView addSubview:self.contentLB];
    
    self.phoneAddressLB = [[UILabel alloc] initWithFrame:CGRectMake(maxX+kMargin10, CGRectGetMaxY(self.contentLB.frame)+kMargin5, ADAPTWidth(200), ADAPTHeight(20))];
    self.phoneAddressLB.font = [UIFont systemFontOfSize:13.0];
    self.phoneAddressLB.textColor = [UIColor whiteColor];
//    self.phoneAddressLB.text = @"15837664444 杭州市滨江区";
    [self.headBgView addSubview:self.phoneAddressLB];
    
    self.dismissBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.dismissBtn setImage:[UIImage imageNamed:@"dismiss"] forState:(UIControlStateNormal)];
    self.dismissBtn.frame = CGRectMake(KWidth - ADAPTWidth(50), CGRectGetMinY(self.shopIconIV.frame)-kMargin5, ADAPTWidth(40), ADAPTWidth(40));
    [self.dismissBtn addTarget:self action:@selector(dismissAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.headBgView addSubview:self.dismissBtn];
}

/**重新给头部视图赋值*/
- (void)reValueShopHeadView {

    // 大背景图
//    [self.headBgView sd_setImageWithURL:[NSURL URLWithString:self.shopModel.avatar] placeholderImage:[UIImage imageNamed:@"p[laceholderImg.png"]];
    
    [self.headBgView sd_setImageWithURL:[NSURL URLWithString:self.shopModel.cover] placeholderImage:[UIImage imageNamed:@"default_shop_bj"]];
    
    [self.shopIconIV sd_setImageWithURL:[NSURL URLWithString:self.shopModel.avatar] placeholderImage:[UIImage imageNamed:@"placeholderImg.png"]];
    
    self.shopTitleLB.text = [NSString stringWithFormat:@"%@",self.shopModel.name];
    self.contentLB.text = [NSString stringWithFormat:@"经营内容:%@",self.shopModel.business];
    self.phoneAddressLB.text = [NSString stringWithFormat:@"%@ %@",self.shopModel.shop_phone,self.shopModel.shop_address];
}

- (void)dismissAction:(UIButton *)btn {

    //两个都写上。
    [self.navigationController popViewControllerAnimated:YES];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

/**label的数量根据titleArr的个数创建*/
- (void)createCategoryViewTitleArr:(NSArray *)titleArr {
    self.titleScrollView = [UIScrollView new];
    
    // config 配置属性
    CGFloat headV_maxY = CGRectGetMaxY(self.headBgView.frame);
    self.titleScrollView.frame = CGRectMake(0, headV_maxY,KWidth , ADAPTHeight(35));
    [self.view addSubview:self.titleScrollView];
    
    CGFloat btn_w = 100;
    CGFloat btn_h = self.titleScrollView.bounds.size.height;
    self.titleScrollView.contentSize = CGSizeMake(btn_w * titleArr.count, btn_h);
    
    for (int i=0; i<titleArr.count; i++) {
        
        XJShopCategoryModel * shopCtyModel = titleArr[i];
        
        RBTitleButton *titleBtn = [self rb_createALabelWithTag:i labelW:btn_w labelH:btn_h title:shopCtyModel.name];
        
        [self.titleScrollView addSubview:titleBtn];
        [self.btnArray addObject:titleBtn];
    }
    
    // 取出第一个button
    // bug:为什么会是6个子视图。前面两个还是imageView；
//    RBTitleButton *firstSelectedBtn = self.titleScrollView.subviews.firstObject;
    
    RBTitleButton *firstSelectedBtn = [self.btnArray firstObject];
    
    // 黄色指示器
    UIView *indicateView = [UIView new];
    indicateView.backgroundColor = [firstSelectedBtn titleColorForState:(UIControlStateSelected)]; // 设置颜色
    indicateView.frame = CGRectMake(0, self.titleScrollView.bounds.size.height-2, btn_w, 2); // 设置frame
    [self.titleScrollView addSubview:indicateView];
    
    self.indicateLine = indicateView;
    
    //提前计算好按钮文字的长度
    [firstSelectedBtn.titleLabel sizeToFit];
    self.indicateLine.rb_width = firstSelectedBtn.titleLabel.rb_width;
    self.indicateLine.rb_center_x = firstSelectedBtn.titleLabel.rb_center_x;
    
    // 默认让第一个选中
    [self clickTitleBtnAction:firstSelectedBtn];
}


- (RBTitleButton *)rb_createALabelWithTag:(int)i labelW:(CGFloat)lb_w labelH:(CGFloat)lb_h title:(NSString *)title{
    RBTitleButton *aBtn = [RBTitleButton buttonWithType:(UIButtonTypeCustom)];
    aBtn.frame = CGRectMake(i*lb_w, 0, lb_w,lb_h);
    aBtn.tag = i; // 设置tag值
    [aBtn setTitle:title forState:(UIControlStateNormal)];
    
    [aBtn addTarget:self action:@selector(clickTitleBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    return aBtn;
}

- (void)clickTitleBtnAction:(RBTitleButton *)btn {
    XJLog(@"点击了第:%ld个btn",btn.tag);
    // 修改按钮选中状态
    self.selectedBtn.selected = NO;
    btn.selected = YES;
    self.selectedBtn = btn;
    
    // 指示器移动
    [UIView animateWithDuration:0.25 animations:^{
        self.indicateLine.rb_width = btn.titleLabel.rb_width;
        self.indicateLine.rb_center_x = btn.rb_center_x;
    }];
    
    // 怎么让btn滚?
    CGFloat offsetX = btn.center.x - KWidth / 2;
    CGFloat maxOffsetX = self.titleScrollView.contentSize.width - KWidth;
    
    // 处理最左边、最右边情况
    if (offsetX<0) {offsetX = 0;}
    if (offsetX>maxOffsetX) {offsetX = maxOffsetX;}
    
    [self.titleScrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    
    //让scrollView滚动
    CGPoint offset = self.scrollView.contentOffset;
    offset.x = btn.tag * self.scrollView.rb_width;
    
    [self.scrollView setContentOffset:offset animated:YES];
}

- (void)rb_setupScrollView {
    XJLog(@"初始化scrollview");
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    CGFloat titleScrollViewBottom = self.titleScrollView.rb_bottom;
    XJLog(@"%f",titleScrollViewBottom);
    
    UIScrollView *scv = [[UIScrollView alloc] initWithFrame:CGRectMake(0, titleScrollViewBottom, KWidth, KHeight - kStatusBarAndNavigationBarHeight - titleScrollViewBottom)];
    scv.backgroundColor = [UIColor lightGrayColor];
    
    scv.delegate = self;
    scv.pagingEnabled = YES;
    
    self.scrollView = scv;
    
    [self.view addSubview:self.scrollView];
    
    // 设置contentSize
    
    NSUInteger count = self.childViewControllers.count;
    self.scrollView.contentSize = CGSizeMake(KWidth * count, 0);
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    [self rb_addChildViews];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //切换按钮状态
    NSInteger index = self.scrollView.contentOffset.x / self.scrollView.rb_width;
    XJLog(@"%ld",index);
    RBTitleButton *btn = self.btnArray[index];
    [self clickTitleBtnAction:btn];
    
    //切换view
    [self rb_addChildViews];
}




#pragma mark - 四 获取店铺详情数据
/**第一次展示:店铺详情+全部分类数据*/
- (void)requestDianPuDetailData {
    
    XJLog(@"shopId:%@",self.shopId);
    [XJHttpTool requestShopInfoId:self.shopId successHandler:^(id responseObjc) {
        
        NSDictionary *shopInfoDic = responseObjc[@"data"][@"shop_info"];
        // 转model
        self.shopModel = [XJShopDetailModel mj_objectWithKeyValues:shopInfoDic[@"shop_detail"]];
        
        NSArray *tempArr = shopInfoDic[@"shop_category"];
        
        //如果有数据才进行后续操作
        if (tempArr.count == 0) {  return ;}
        
        for (NSDictionary *ctgyDic in tempArr) {
            XJShopCategoryModel *ctgyModel = [XJShopCategoryModel mj_objectWithKeyValues:ctgyDic];
            [self.shopCategoryArr addObject:ctgyModel];
        }
        
        
        
        // 主线程刷新
        dispatch_async(dispatch_get_main_queue(), ^{
            
            // 上面的分类view
            [self createShopHeadView];
            [self createCategoryViewTitleArr:self.shopCategoryArr.copy];
            
            // 下面对应的分类详情view
            [self rb_addChildVCs:self.shopCategoryArr.copy];

            [self rb_setupScrollView];
            
            [self rb_addChildViews];
            
            [self reValueShopHeadView];
        });
        
    } failureHandler:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}



/**获取全部分类数据*/
- (void)requestAllCategoryData {
    NSLog(@"%@",self.shopId);
    
    //无数据,咋搞。
    NSDictionary *allCategoryDic = @{@"shop_id":self.shopId,@"shop_goods_category_id":@"0"};
    [XJHttpTool requestShopCategoryDic:allCategoryDic successHandler:^(id responseObjc) {

    } failHandler:^(NSError *error) {

    }];
}



- (void)dealloc {
    XJLog(@"%s--%d 销毁",__FUNCTION__,__LINE__);
}
@end
